#ifndef KERNEL_AGV_AGV_ENTITY_H
#define KERNEL_AGV_AGV_ENTITY_H

#include <string>
#include <vector>
#include <functional>
#include <chrono>

namespace kernel {
namespace agv {

enum class NavStatus {
    None = 0,       // 无任务
    Waiting = 1,    // 等待中（目前不可能出现该状态）
    Running = 2,    // 导航中
    Suspended = 3,  // 暂停
    Completed = 4,  // 完成
    Failed = 5,     // 失败
    Canceled = 6    // 取消
};

enum class TaskType {
    None = 0,
    FreeNav = 1,           // 自由导航到任意点
    FreeNavToStation = 2,  // 自由导航到站点
    PathNavToStation = 3,  // 路径导航到站点
    Translate = 7,         // 平动转动
    Other = 100            // 其他
};

enum class AgvMode {
    Manual = 0,
    Automatic = 1
};

enum class AgvType {
    MKLM = 0,   // 米克力美 AGV
    SEER = 1    // Seer AGV
};

struct Position {
    double x{0.0};
    double y{0.0};
    double angle{0.0};

    Position() = default;
    Position(double x_, double y_, double angle_)
        : x(x_), y(y_), angle(angle_) {}
};

struct ErrorInfo {
    std::string errorCode;
    std::string errorMessage;
    std::chrono::system_clock::time_point timestamp;
};

// AGV领域实体 - 纯业务逻辑，无基础设施依赖
class AgvEntity {
public:
    AgvEntity(int agvId, int agvNumber);
    ~AgvEntity() = default;

    // 禁用拷贝，允许移动
    AgvEntity(const AgvEntity&) = delete;
    AgvEntity& operator=(const AgvEntity&) = delete;
    AgvEntity(AgvEntity&&) = default;
    AgvEntity& operator=(AgvEntity&&) = default;

    // 基础信息访问器
    int getId() const { return m_id; }
    int getNumber() const { return m_number; }
    AgvType getType() const { return m_type; }
    std::string getIpAddress() const { return m_ipAddress; }
    std::string getCurrentMap() const { return m_currentMap; }

    // 位置信息
    Position getPosition() const { return m_position; }
    std::string getCurrentStation() const { return m_currentStation; }
    std::string getLastStation() const { return m_lastStation; }
    std::string getTargetStation() const { return m_targetStation; }

    // 状态信息
    int getBatteryLevel() const { return m_batteryLevel; }
    double getConfidence() const { return m_confidence; }
    bool isOnline() const { return m_isOnline; }
    bool isCharging() const { return m_isCharging; }
    bool isBlocked() const { return m_isBlocked; }
    bool isLocked() const { return m_isLocked; }

    // 任务状态
    NavStatus getNavStatus() const { return m_navStatus; }
    TaskType getTaskType() const { return m_taskType; }
    bool isBusy() const { return m_isBusy; }
    bool isControlledByDispatcher() const { return m_isControlledByDispatcher; }

    // 路径信息
    const std::vector<std::string>& getFinishedPath() const { return m_finishedPath; }
    const std::vector<std::string>& getUnfinishedPath() const { return m_unfinishedPath; }
    const std::vector<std::string>& getCurrentAreas() const { return m_currentAreas; }

    // 错误信息
    const std::vector<ErrorInfo>& getErrors() const { return m_errors; }

    // 状态设置器（由应用层调用）
    void setType(AgvType type) { m_type = type; }
    void setIpAddress(const std::string& ip) { m_ipAddress = ip; }
    void setCurrentMap(const std::string& mapName) { m_currentMap = mapName; }
    void setPosition(const Position& pos) { m_position = pos; }
    void setCurrentStation(const std::string& station) { m_currentStation = station; }
    void setLastStation(const std::string& station) { m_lastStation = station; }
    void setTargetStation(const std::string& station) { m_targetStation = station; }

    void setBatteryLevel(int level) { m_batteryLevel = level; }
    void setConfidence(double confidence) { m_confidence = confidence; }
    void setOnlineStatus(bool online) { m_isOnline = online; }
    void setChargingStatus(bool charging) { m_isCharging = charging; }
    void setBlockedStatus(bool blocked) { m_isBlocked = blocked; }
    void setLockedStatus(bool locked) { m_isLocked = locked; }

    void setNavStatus(NavStatus status) { m_navStatus = status; }
    void setTaskType(TaskType type) { m_taskType = type; }
    void setBusyStatus(bool busy) { m_isBusy = busy; }
    void setControlledByDispatcher(bool controlled) { m_isControlledByDispatcher = controlled; }

    void setFinishedPath(const std::vector<std::string>& path) { m_finishedPath = path; }
    void setUnfinishedPath(const std::vector<std::string>& path) { m_unfinishedPath = path; }
    void setCurrentAreas(const std::vector<std::string>& areas) { m_currentAreas = areas; }
    void setErrors(const std::vector<ErrorInfo>& errors) { m_errors = errors; }

    // 业务逻辑方法
    bool needsCharging() const;
    bool canAcceptTask() const;
    bool isAtStation(const std::string& stationName) const;
    double getDistanceTo(double x, double y) const;

    // 时间戳管理
    void updateLastUploadTime();
    void updateLastBusyTime();
    std::chrono::system_clock::time_point getLastUploadTime() const { return m_lastUploadTime; }
    std::chrono::system_clock::time_point getLastBusyTime() const { return m_lastBusyTime; }

    // 任务计数（用于调度）
    int getTaskRequestCount() const { return m_taskRequestCount; }
    void incrementTaskRequestCount() { m_taskRequestCount++; }
    void resetTaskRequestCount() { m_taskRequestCount = 0; }

private:
    // 标识
    int m_id;                    // 调度系统内部ID
    int m_number;                // AGV编号（写在车上的编号）
    AgvType m_type{AgvType::MKLM}; // AGV类型
    std::string m_ipAddress;
    std::string m_currentMap;

    // 位置状态
    Position m_position;
    std::string m_currentStation;
    std::string m_lastStation;
    std::string m_targetStation;

    // 物理状态
    int m_batteryLevel{100};
    double m_confidence{1.0};
    bool m_isOnline{false};
    bool m_isCharging{false};
    bool m_isBlocked{false};
    bool m_isLocked{false};

    // 任务状态
    NavStatus m_navStatus{NavStatus::None};
    TaskType m_taskType{TaskType::None};
    bool m_isBusy{false};
    bool m_isControlledByDispatcher{false};

    // 路径信息
    std::vector<std::string> m_finishedPath;
    std::vector<std::string> m_unfinishedPath;
    std::vector<std::string> m_currentAreas;

    // 错误信息
    std::vector<ErrorInfo> m_errors;

    // 时间戳
    std::chrono::system_clock::time_point m_lastUploadTime;
    std::chrono::system_clock::time_point m_lastBusyTime;

    // 调度相关
    int m_taskRequestCount{0};
};

/**
 * @brief 将字符串转换为 AgvType 枚举
 * @param typeStr 车型字符串(不区分大小写,如 "SEER", "MKLM")
 * @return AgvType 枚举值(无效时返回 std::nullopt)
 */
inline std::optional<AgvType> agvTypeFromString(const std::string& typeStr) {
    // 去除前后空格并转换为大写
    std::string upper;
    size_t start = 0;
    while (start < typeStr.size() && typeStr[start] == ' ') {
        ++start;
    }
    size_t end = typeStr.size();
    while (end > start && typeStr[end - 1] == ' ') {
        --end;
    }

    for (size_t i = start; i < end; ++i) {
        char c = typeStr[i];
        if (c >= 'a' && c <= 'z') {
            c = c - 'a' + 'A';
        }
        upper += c;
    }

    if (upper == "SEER") {
        return AgvType::SEER;
    }
    if (upper == "MKLM") {
        return AgvType::MKLM;
    }
    return std::nullopt;
}

/**
 * @brief 将 AgvType 枚举转换为字符串
 * @param type 车型枚举
 * @return 车型字符串
 */
inline std::string agvTypeToString(AgvType type) {
    switch (type) {
        case AgvType::SEER:
            return "SEER";
        case AgvType::MKLM:
            return "MKLM";
        default:
            return "UNKNOWN";
    }
}

} // namespace agv
} // namespace kernel

#endif // KERNEL_AGV_AGV_ENTITY_H
